/*-------------------------------------------------------------------------*/
/**
  @file		plotlib_general.c
  @author	Renaud Wanschoor
  @date	july 2004
  @version	$Revision: 2.3 $
  @brief	contains plib functions that are not specific to a graph or a grid

  plib functions are used to serialize matchings sequences and results of each
  level of the uncoarsening stage. They are currently used for METIS and PaGrid
  pagridplot also used plib functions.

  there are also utilities used by pagrid in plib, those are error handling,
  memory allocation, priority queues, randum number generator, dll as macros,
  io functions, in fact all utils that may used for other programs.
  
*/
/*--------------------------------------------------------------------------*/

#include "plib.h"

FILE* PLIB_SerializeInit(int tool, int count,
			 char *filename,int outresult, int id,
			 char* F_graph, char* F_grid,
			 int CType, int WType, int RType,
			 int CSeed, int ISeed, int RSeed){
  int bool = 1;
  char buf[PLIB_STR];
  FILE* fp;

  if(outresult == IO_OUT_LEVEL)
    sprintf(buf,"matching.%d.%s",id,filename);
  else
    sprintf(buf,"matching.%s",filename);
  strcpy(filename,buf);

  WARNING(((fp = fopen(filename,"wb")) == NULL,"PLIB_SerializeInit error code 1 : cannot open %s\n",filename),NULL);

  /* tool */
  bool = fwrite(&tool,sizeof(int),1,fp) && bool;
  
  /* graph & grid file */
  bool = U_serializeStr(F_graph,fp) && bool;
  bool = U_serializeStr(F_grid,fp) && bool;

  /* matching scheme */
  bool = fwrite(&CType,sizeof(int),1,fp) && bool;
  /* edge weight */
  bool = fwrite(&WType,sizeof(int),1,fp) && bool;
  /* refinement scheme */
  bool = fwrite(&RType,sizeof(int),1,fp) && bool;
  /* randomness */
  bool = fwrite(&CSeed,sizeof(int),1,fp) && bool;
  bool = fwrite(&ISeed,sizeof(int),1,fp) && bool;
  bool = fwrite(&RSeed,sizeof(int),1,fp) && bool;

  /* number of graphs */
  bool = fwrite(&count,sizeof(int),1,fp) && bool;

  return fp;
}

FILE* PLIB_UnserializeInit(int* tool, char *F_ser, char **F_graph, char **F_grid,
			   int* level, int* CType, int* WType, int *RType,
			   int* CSeed, int *ISeed, int *RSeed){
  FILE* fp;
  char *graphfile, *gridfile;
  
  WARNING(((fp = fopen(F_ser,"rb")) == NULL,"PLIB_UnserializeInit error code 1 : cannot open %s\n",F_ser),NULL);

  /* tool */
  fread(tool,sizeof(int),1,fp);

  graphfile = U_unserializeStr(fp);
  gridfile  = U_unserializeStr(fp);

  if(F_graph != NULL){
    *F_graph  = graphfile;
    graphfile = NULL;
  }
  if(F_grid != NULL){
    *F_grid  = gridfile;
    gridfile = NULL;
  } 

  /* matching scheme */
  fread(CType,sizeof(int),1,fp);
  /* edge weight */
  fread(WType,sizeof(int),1,fp);
  /* refinement scheme */
  fread(RType,sizeof(int),1,fp);
  /* randomness */
  fread(CSeed,sizeof(int),1,fp);
  fread(ISeed,sizeof(int),1,fp);
  fread(RSeed,sizeof(int),1,fp);

  fread(level,sizeof(int),1,fp);

  return fp;
}
